package cn.edu.ncu.housinghub.utils.security;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 邮件发送工具类
 */
@Component
public class MailUtil {
    // 注入专门用于验证码的RedisTemplate
    @Resource(name = "verificationRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;
    @Value("${app.redis.verification-db}")
    private static JavaMailSender javaMailSender;
    private static String sender;
    private static StringRedisTemplate emailRedisTemplate;

    // 验证码过期时间（分钟）
    private static final long VERIFICATION_CODE_EXPIRE = 5;
    // 存储邮箱验证码的Map，实际项目中应使用Redis等缓存
    private static final Map<String, String> verificationCodeMap = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        javaMailSender = mailSender;
        sender = from;
        emailRedisTemplate = redisTemplate;
    }

    /**
     * 发送验证码邮件
     * @param receiver 收件人邮箱
     */
    public static void sendVerificationCode(String receiver) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 验证邮箱格式是否为QQ邮箱
        if (!receiver.matches("^[a-zA-Z0-9_-]+@qq.com$")) {
            throw new BusinessException(ErrorCodeConstant.INVALID_EMAIL_FORMAT);
        }
        // 如果邮箱不存在
        /*if (!emailRedisTemplate.hasKey(receiver))
            throw new BusinessException(ErrorCodeConstant.EMAIL_NOT_EXIST);*/
        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        message.setFrom(sender);
        message.setTo(receiver);
        message.setSubject("【HousingHub】注册验证码");
        message.setText("您的注册验证码是：" + code + "，有效期为" +
                VERIFICATION_CODE_EXPIRE +
                "分钟，请勿泄露和转发。" +
                "如非本人操作，请忽略此短信。");

        javaMailSender.send(message);

        // 将验证码存储到redis中

        emailRedisTemplate.opsForValue().set(
                SystemConstant.VERIFICATION_CODE_PREFIX.getStringValue()
                        +receiver,
                 code,
                SystemConstant.VERIFICATION_CODE_EXPIRE_TIME.getIntegerValue(),
                TimeUnit.MINUTES);
        // 将验证码存储到Map中，实际项目中应存储到Redis并设置过期时间
//        verificationCodeMap.put(receiver, code);
    }

    /**
     * 验证邮箱验证码
     * @param receiver 邮箱
     * @param code 验证码
     * @return 是否验证通过
     */
    public static boolean verifyCode(String receiver, String code) {
//        String storedCode = verificationCodeMap.get(receiver);
        // 从Redis中获取验证码
        String storedCode = emailRedisTemplate.opsForValue().get(
                SystemConstant.VERIFICATION_CODE_PREFIX.getStringValue()
                +receiver);
        if (storedCode == null) {
            return false;
        }
        return storedCode.equals(code);
    }

    /**
     * 清除验证码
     * @param email 邮箱
     */
    public static void clearCode(String email) {
        // 从redis中删除验证码
        emailRedisTemplate.delete(
                SystemConstant.VERIFICATION_CODE_PREFIX.getStringValue()
                +email);
//        verificationCodeMap.remove(email);
    }
}
